package com.yakaten.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.seasar.framework.log.Logger;
import org.seasar.framework.util.ResourceUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.amazonaws.mws.MarketplaceWebService;
import com.amazonaws.mws.MarketplaceWebServiceClient;
import com.amazonaws.mws.MarketplaceWebServiceConfig;
import com.amazonaws.mws.MarketplaceWebServiceException;
import com.amazonaws.mws.model.FeedSubmissionInfo;
import com.amazonaws.mws.model.IdList;
import com.amazonaws.mws.model.SubmitFeedRequest;
import com.amazonaws.mws.model.SubmitFeedResponse;
import com.amazonaws.mws.model.SubmitFeedResult;
import com.yakaten.dto.AmazonPriceTaskDto;
import com.yakaten.exception.AmazonException;

public class AmazonWebservice {

	static Logger logger = Logger.getLogger(AmazonWebservice.class);
	final String merchantId = ResourceUtil.getProperties("yakaten.properties")
			.getProperty("amazon.mws.sellerid");

	String feedFilePath = ResourceUtil.getProperties("yakaten.properties")
			.getProperty("amazon.mws.updateprice.feedfilepath");
	
	String formatFilePath = ResourceUtil.getProperties("yakaten.properties")
	.getProperty("amazon.mws.updateprice.formatfilepath");
	
	

	public void updateItemPrice(List<AmazonPriceTaskDto> itemList)
			throws AmazonException {
		final String accessKeyId = ResourceUtil.getProperties(
				"yakaten.properties").getProperty("amazon.mws.accesskeyid");
		final String secretAccessKey = ResourceUtil.getProperties(
				"yakaten.properties").getProperty("amazon.mws.accesskey");

		final String appName = ResourceUtil.getProperties(
		"yakaten.properties").getProperty("system.appname");
		final String appVersion = ResourceUtil.getProperties(
		"yakaten.properties").getProperty("system.appversion");

		MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();

		// Japan
		config.setServiceURL("https://mws.amazonservices.jp");

		MarketplaceWebService service = new MarketplaceWebServiceClient(
				accessKeyId, secretAccessKey, appName, appVersion, config);

		final String marketPlaceId = ResourceUtil.getProperties(
				"yakaten.properties").getProperty("amazon.mws.maketplace");

		final IdList marketplaces = new IdList(Arrays.asList(marketPlaceId));

		SubmitFeedRequest request = new SubmitFeedRequest();
		request.setMerchant(merchantId);
		request.setMarketplaceIdList(marketplaces);

		request.setFeedType("_POST_PRODUCT_PRICING_DATA_");

		try {
			File feedFile = getFeedFile(itemList);
			request.setFeedContent(new FileInputStream(feedFile));
			String feedSessionId = invokeSubmitFeed(service, request);
			String message = " >>>fileName:" + feedFile.getName()
					+ " feedSessionId:" + feedSessionId;
			
			if(feedSessionId!=null && feedSessionId.length()>0){
				feedFile.delete();
			}
			if(logger.isInfoEnabled()){
				logger.info(message);
			}
		} catch (FileNotFoundException e) {
			throw new AmazonException(e);
		} catch (SAXException e) {
			throw new AmazonException(e);
		} catch (IOException e) {
			throw new AmazonException(e);
		} catch (ParserConfigurationException e) {
			throw new AmazonException(e);
		} catch (TransformerException e) {
			throw new AmazonException(e);
		} catch (MarketplaceWebServiceException e) {
			throw new AmazonException(e);
		}

	}

	private File getFeedFile(List<AmazonPriceTaskDto> itemList)
			throws SAXException, IOException, ParserConfigurationException,
			TransformerException {
		javax.xml.parsers.DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		javax.xml.parsers.DocumentBuilder builder = factory
				.newDocumentBuilder();

		String formatFileName = ResourceUtil
				.getProperties("yakaten.properties").getProperty(
						"amazon.mws.updateprice.filename");
		Document doc = builder.parse(formatFilePath + formatFileName);

		String outputFileName = "" + (new Date().getTime()) + ".xml";
		File returnfile = new File(feedFilePath + outputFileName);
		Element merchantIdElement = (Element) doc.getElementsByTagName(
				"MerchantIdentifier").item(0);
		merchantIdElement.setTextContent(merchantId);

		int i = 1;
		for (AmazonPriceTaskDto current : itemList) {
			Element message = doc.createElement("Message");
			Element messageId = doc.createElement("MessageID");
			messageId.setTextContent("" + i);
			message.appendChild(messageId);

			Element price = doc.createElement("Price");
			Element sku = doc.createElement("SKU");
			sku.setTextContent(current.getShopItemId());
			Element standardPrice = doc.createElement("StandardPrice");
			standardPrice.setTextContent("" + current.getShopItemPrice());
			standardPrice.setAttribute("currency", "JPY");
			price.appendChild(sku);
			price.appendChild(standardPrice);

			message.appendChild(price);
			doc.getElementsByTagName("AmazonEnvelope").item(0).appendChild(
					message);
			i++;
		}

		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(
				"{http://xml.apache.org/xslt}indent-amount", "2");
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(returnfile);
		transformer.transform(source, result);
		return returnfile;
	}

	public static void main(String[] args) {
		try {
			List<AmazonPriceTaskDto> list = new ArrayList<AmazonPriceTaskDto>();
			AmazonPriceTaskDto dto1 = new AmazonPriceTaskDto();
			dto1.setShopItemId("4560209968779");
			dto1.setShopItemPrice(68625);

//			AmazonPriceTaskDto dto2 = new AmazonPriceTaskDto();
//			dto2.setShopItemId("4547597733059--");
//			dto2.setShopItemPrice(200998);

			list.add(dto1);
//			list.add(dto2);

			new AmazonWebservice().updateItemPrice(list);
		} catch (AmazonException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Submit Feed request sample Uploads a file for processing together with
	 * the necessary metadata to process the file, such as which type of feed it
	 * is. PurgeAndReplace if true means that your existing e.g. inventory is
	 * wiped out and replace with the contents of this feed - use with caution
	 * (the default is false).
	 *
	 * @param service
	 *            instance of MarketplaceWebService service
	 * @param request
	 *            Action to invoke
	 * @throws MarketplaceWebServiceException
	 */
	private String invokeSubmitFeed(MarketplaceWebService service,
			SubmitFeedRequest request) throws MarketplaceWebServiceException {
		String feedSubmissionId = "";

		SubmitFeedResponse response = service.submitFeedFromFile(request);

		if (response.isSetSubmitFeedResult()) {
			SubmitFeedResult submitFeedResult = response.getSubmitFeedResult();
			if (submitFeedResult.isSetFeedSubmissionInfo()) {
				FeedSubmissionInfo feedSubmissionInfo = submitFeedResult
						.getFeedSubmissionInfo();
				if (feedSubmissionInfo.isSetFeedSubmissionId()) {
					feedSubmissionId = feedSubmissionInfo.getFeedSubmissionId();
				}
			}
		}

		return feedSubmissionId;
	}

}
